<template>
  <el-page-header @back="goBack">
    <template #content>
      <div style="display: flex; align-items: center;">
        <el-avatar
            :size="40"
            :src=userPic
        />
        <el-tag style="margin-left: 5px;padding: 12px 14px;font-size: 14px">{{ userName }}</el-tag>
        <span style="margin-left: 10px; font-size: 18px; font-weight: bold">{{ title }}</span>
      </div>
    </template>
    <template #extra>
      <div class="flex items-center">
        <img src="@/assets/images/like.gif" style="width: 200px; height: 50px; vertical-align: middle;">
        <el-button style="vertical-align: middle;">点赞</el-button>
        <el-button type="primary" style="vertical-align: middle;margin-right: 20px">收藏</el-button>
      </div>
    </template>
  </el-page-header>
  <el-container>

      <el-container>
      <el-aside width="75%" class="sticky-aside">
        <div class="article-page">
          <div id="nice" class="article-content" v-html="renderedMarkdown"></div>
        </div>
      </el-aside>
      <el-main>
        <el-card class="box-card">
          <div style="font-size: 20px;font-weight: bold;margin-bottom: 5px">
              文章标题
          </div>
          <div v-for="i in 8" style="margin: 5px auto">
            标题{{i}}
          </div>
        </el-card>
        <el-card class="box-card" style="margin-top: 20px">
          <div style="font-size: 20px;font-weight: bold;margin-bottom: 10px">
            评论
            <el-button @click="dialogVisible = true" style="vertical-align: middle;margin: 0 10px;float: right">评论</el-button>
          </div>
          <div v-for="item in comments" style="margin: 5px auto">
            <div style="display: flex;margin-top: 10px">
              <img :src="item.userPic" style="width: 34px;height: 34px;border-radius: 50%">
              <div style="margin-left: 10px;width: 100%">
                <div style="font-size: 14px;font-weight: bold">
                  {{ item.nickname }}
                </div>
                <div style="font-size: 12px;color: rgb(125, 126, 138)">
                  {{ item.updateTime }} IP:嘉兴
                </div>
                <div style="margin-top: 5px;letter-spacing: 1.1px;font-size: 14px;">
                  {{ item.content }}
                </div>
                <div style="display: flex;margin: 7px 0px 3px 0px">
                  <span style="color: #999999;margin-right: 10px;">
                    <img src="@/assets/icon/thumbs_up.png" style="width: 16px;margin-right: 5px"></span>
                  <span style="color: #999999;padding-right: 10px">
                    <img src="@/assets/icon/collection.png" style="width: 20px;margin-right: 5px">
                  </span>
                  <span style="color: #999999;padding-right: 12px" @click="reply(item.id)">
                    <img src="@/assets/icon/comment.png" style="width: 16px;">
                  </span>
                </div>
                <div v-if="item.sonComments && item.sonComments.length > 0" style="background-color: rgb(236, 248, 254);padding: 2px;border-radius: 5px;width: 100%">
                  <div v-for="son in item.sonComments" style="margin: 3px;display: flex;font-size: 13px">
                    {{ son.nickname }}：{{ son.content }}
                  </div>
                </div>
              </div>
            </div>
          </div>


        </el-card>

        <el-dialog v-model="dialogVisible" title="评论" width="500" draggable :show-close="false">
              <input type="text"  class="to_comment" v-model="commentText" placeholder="请输入评论内容">
              <img :src="userInfoStore.info.userPic" style="width: 40px; border-radius: 50%; margin-left: 10px;">
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="cancelReply">取消</el-button>
              <el-button type="primary" @click="send_comment">
                发送
              </el-button>
            </div>
          </template>
        </el-dialog>
      </el-main>
      </el-container>

  </el-container>


</template>

<script setup>
import { ref, onMounted } from 'vue';
import { marked } from 'marked';
// import textContent from '../../../assets/md/text.md?raw'; // 使用 raw 导入
import '../../../assets/css/markdown_blue.css';
import { articleDetailService } from '@/api/admin/article.js';
import {useRoute} from "vue-router";
import {userSearchService} from "@/api/admin/user.js";
import {commentAddService, commentListService, sonCommentListService} from "@/api/admin/comment.js"
import useUserInfoStore from '@/stores/userinfo.js'
const userInfoStore = useUserInfoStore();
import {ElMessage} from "element-plus";

const renderedMarkdown = ref('');
const comments = ref([]);


// onMounted(() => {
//   // 将 Markdown 转换为 HTML
//   renderedMarkdown.value = marked(response.content);
// });
const dialogVisible = ref(false)
const replyUser = ref(0)
const commentText = ref('')
const route = useRoute();
const title = ref('');
const articleId = ref('')
const userName = ref('')
const userPic = ref('')


const send_comment = async () => {
  const commentData = {
    content: commentText.value,
    articleId: articleId.value,
    userId: userInfoStore.info.id,
    replyUser: replyUser.value
  };
  await commentAddService(commentData).then(res => {
    ElMessage.success('评论成功')
    dialogVisible.value = false
    replyUser.value = 0
    commentText.value = ''
    fetchArticle();
  }).catch(error => {
    console.error('Error:', error); // 输出错误信息
    ElMessage.error('评论失败');
  });
}

const  reply = (id) => {
  replyUser.value = id
  dialogVisible.value = true
}

const cancelReply = () => {
  dialogVisible.value = false
  replyUser.value = 0
}


const fetchArticle = async () => {
  const id = route.params.id;
  articleId.value = id;
  const response = await articleDetailService(id);
  title.value = response.data.title;
  const user = await userSearchService(response.data.createUser);
  userName.value = user.data.nickname;
  userPic.value = user.data.userPic;
  const commentList = await commentListService(id);
  comments.value = commentList.data.map(comment => ({
    ...comment,
    sonComments: [], // 初始化 sonComments 为一个空数组
    nickname: '' // 初始化 nickname 为一个空字符串
  }));

  // 获取每个评论的用户昵称
  for (let i = 0; i < comments.value.length; i++) {
    const comment = comments.value[i];
    const commentUser = await userSearchService(comment.createUser);
    comment.nickname = commentUser.data.nickname;
    comment.userPic = commentUser.data.userPic;

    // 获取子评论及其用户昵称
    const sonCommentList = await sonCommentListService(comment.id);
    comment.sonComments = sonCommentList.data.map(sonComment => ({
      ...sonComment,
      nickname: ''
    }));

    for (let j = 0; j < comment.sonComments.length; j++) {
      const sonComment = comment.sonComments[j];
      const sonCommentUser = await userSearchService(sonComment.createUser);
      sonComment.nickname = sonCommentUser.data.nickname;
      sonComment.userPic = sonCommentUser.data.userPic;
    }
  }

  renderedMarkdown.value = marked(response.data.content);
};

onMounted(fetchArticle);


const goBack = () => {
  window.history.back();
};
</script>

<style scoped>
.article-page {
  padding: 20px;
  border: 1px solid #ccc;
  margin: 20px;
}

.sticky-aside {
  position: sticky;
  top: 0; /* 固定在顶部 */
  overflow-y: auto; /* 启用垂直滚动条 */
  max-height: 100vh; /* 设置最大高度为视口高度 */
}

.sticky-aside::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

.sticky-main {
  position: sticky;
  top: 0; /* 固定在顶部 */
  overflow-y: auto; /* 启用垂直滚动条 */
  max-height: 80vh; /* 设置最大高度为视口高度 */
}
.sticky-main::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

.to_comment{
  width: 390px;
  border: 1px solid #ccc;
  margin-top: 5px;
  border-radius: 5px;
  padding: 10px;
  float: right;
}
</style>
